#!/usr/bin/env  python
# -*- coding：utf-8 -*-

import os,sys
import time
import pycurl
import StringIO
import json
import MySQLdb
import urllib
#reload(sys)
#sys.setdefaultencoding('utf-8')

conn = MySQLdb.connect(host='10.16.48.81',user='root',passwd='123',db='webserver',port=3306,charset="utf8")
cur = conn.cursor()

def checkurl(demo):
        URL = demo[4]
        c = pycurl.Curl()
        b = StringIO.StringIO()
        c.setopt(pycurl.WRITEFUNCTION, b.write)
        c.setopt(c.URL, URL)
        c.setopt(pycurl.CONNECTTIMEOUT, 20) 
        c.setopt(pycurl.TIMEOUT, 20) 
        c.setopt(pycurl.NOPROGRESS, 1) 
        c.setopt(pycurl.FORBID_REUSE, 1)
        c.setopt(pycurl.MAXREDIRS, 1)
        c.setopt(pycurl.DNS_CACHE_TIMEOUT, 30)

        try:
                c.perform()
                html=b.getvalue()
        except Exception,e:
                print "connection error:" + str(e)
                c.close()

        NAMELOOKUP_TIME = c.getinfo(c.NAMELOOKUP_TIME)
        CONNECT_TIME = c.getinfo(c.CONNECT_TIME)
        PRETRANSFER_TIME = c.getinfo(c.PRETRANSFER_TIME)
        STARTTRANSFER_TIME = c.getinfo(c.STARTTRANSFER_TIME)
        TOTAL_TIME = c.getinfo(c.TOTAL_TIME)
        HTTP_CODE = c.getinfo(c.HTTP_CODE)
        SIZE_DOWNLOAD = c.getinfo(c.SIZE_DOWNLOAD)
        HEADER_SIZE = c.getinfo(c.HEADER_SIZE)
        SPEED_DOWNLOAD = c.getinfo(c.SPEED_DOWNLOAD)
        c.close()

        if int(TOTAL_TIME*1000) < 200: #判断请求接口需要的总时间是否大于200ms 如果大于 mysql中fail加1  反之 sucsses加1
                sql = "update kpicount_counts set sucsses=(sucsses+1) where description='%s';" %demo[3]
                cur.execute(sql)
        else:
                sql = "update kpicount_counts set fail=(fail+1) where description='%s';" %demo[3]
                cur.execute(sql)
        conn.commit()

        pre = "select round((1-(fail/sucsses)),4)*100 from kpicount_counts where description='%s';" %demo[3]
        cur.execute(pre)
        bfb = cur.fetchall()
        if int(bfb[0][0]) > 100:
                values = str(NAMELOOKUP_TIME*1000) + ' ' +  str(CONNECT_TIME*1000) + ' ' + str(PRETRANSFER_TIME*1000) + ' ' + str(STARTTRANSFER_TIME*1000) + ' ' + str(TOTAL_TIME*1000) + ' ' + "99.99"
        else:
                values = str(NAMELOOKUP_TIME*1000) + ' ' +  str(CONNECT_TIME*1000) + ' ' + str(PRETRANSFER_TIME*1000) + ' ' + str(STARTTRANSFER_TIME*1000) + ' ' + str(TOTAL_TIME*1000) + ' ' + "%s" % bfb[0][0]
        sql = "insert into kpicount_datas (times,usergroup,username,description,urlvalues) values('%s','%s','%s','%s','%s')" %(time.strftime('%Y-%m-%d-%H:%M:%S'),demo[1],demo[2],demo[3],values)
        cur.execute(sql)
        conn.commit()

sql = "select * from kpicount_urls;"
cur.execute(sql)
data = cur.fetchall()
for x in data:
        checkurl(x)